package top.forlenet.dao.impl;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import top.forlenet.dao.SignDao;
import top.forlenet.entity.Sign;
import top.forlenet.utils.DruidUtils;
import top.forlenet.vo.InviteVO;
import top.forlenet.vo.SignVO;

import java.sql.SQLException;
import java.util.List;

public class SignDaoImpl implements SignDao {
    @Override
    public void insert(Sign sign) {
        QueryRunner queryRunner = DruidUtils.getQueryRunner();
        String sql = "insert into sign(uid, point) values(?,?)";
        try {
            queryRunner.update(sql, sign.getUid(), sign.getPoint());
        } catch (SQLException e) {
            throw new RuntimeException("添加签到信息异常");
        }
    }

    @Override
    public int todaySignCount(Integer uid) {
        QueryRunner queryRunner = DruidUtils.getQueryRunner();
        String sql = "select count(*) from sign where uid=? and date_format(signTime,'%Y%m%d')=date_format(now(), '%Y%m%d')";
        try {
            Long count = queryRunner.query(sql, new ScalarHandler<Long>(), uid);
            return count.intValue();
        } catch (SQLException e) {
            throw new RuntimeException("统计当天签到次数异常");
        }
    }

    @Override
    public List<SignVO> selectList(Integer uid) {
        QueryRunner queryRunner = DruidUtils.getQueryRunner();
        String sql = "SELECT s.id,u.phone,s.signTime, s.point\n" +
                "FROM `sign` s\n" +
                "inner join user u\n" +
                "on s.uid=u.id\n" +
                "where s.uid=? order by s.signTime desc";
        try {
            return queryRunner.query(sql, new BeanListHandler<SignVO>(SignVO.class), uid);
        } catch (SQLException e) {
            throw new RuntimeException("查询签到记录异常");
        }
    }

    @Override
    public List<InviteVO> sumPoint(Integer uid) {
        String sql = "select s.uid id, c.phone, c.registerTime, sum(s.point) totalPoint \n" +
                "from user p\n" +
                "inner join user c\n" +
                "on p.id=c.pid\n" +
                "inner join sign s\n" +
                "on c.id=s.uid\n" +
                "where p.id=?\n" +
                "group by s.uid,c.phone,c.registerTime";
        QueryRunner queryRunner = DruidUtils.getQueryRunner();
        try {
            return queryRunner.query(sql, new BeanListHandler<InviteVO>(InviteVO.class), uid);
        } catch (SQLException e) {
            throw new RuntimeException("统计邀请人信息异常");
        }
    }
}
